package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.heima.behavior.service.LikeService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.util.RequestContextUtil;
import com.heima.model.behavior.dtos.LikeDto;
import com.heima.model.behavior.pojos.LikeDoc;
import com.heima.model.common.dtos.ResponseResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class LikeServiceImpl implements LikeService {
    @Autowired
    MongoTemplate mongoTemplate;
    /**
     * 用户行为——(文章)点赞/取消点赞
     * @param dto
     * @return
     */
    @Override
    public ResponseResult likeBehavior(LikeDto dto) {
        LikeDoc likeDoc = new LikeDoc();
        Integer userId=RequestContextUtil.get("id");
            //判断是否点赞过，如果是不做任何操作，如果不是添加点赞记录
            Query query = Query.query(Criteria.where("userId").is(userId)
            .and("articleId").is(dto.getArticleId()));
            long count = mongoTemplate.count(query, LikeDoc.class);
            if (count<=0) {
                BeanUtils.copyProperties(dto, likeDoc);
                likeDoc.setUserId(userId);
                likeDoc.setArticleId(dto.getArticleId());
                likeDoc.setCreatedTime(new Date());
                likeDoc.setId(IdWorker.getId());
                mongoTemplate.insert(likeDoc);
                System.out.println("点赞成功！");
                return ResponseResult.okResult();
            } else {
            //取消点赞-》删除记录
            Query query1 = Query.query(Criteria.where("userId").is(userId)
            .and("articleId").is(dto.getArticleId()));
            mongoTemplate.remove(query1, LikeDoc.class);
            System.out.println("取消点赞！");
            return ResponseResult.okResult();
        }
    }

    /**
     * 数据回显——点赞
     * @param userId
     * @param articleId
     * @return
     */
    @Override
    public Boolean isLike(int userId, Long articleId) {
        Query query = Query.query(Criteria.where("userId").is(userId).and("articleId").is(articleId));
        long count = mongoTemplate.count(query, LikeDoc.class);
        if (count <= 0) {
            return false;
        } else {
            return true;
        }
    }
}
